//
//  LoginViewController.m
//  auditorias
//
//  Created by Mauro on 7/26/13.
//  Copyright (c) 2013 Antilope. All rights reserved.
//

#import "LoginViewController.h"
#import "KeyboardManager.h"
#import "MBProgressHUD.h"
#import "DataLoader.h"
#import "SharedMemory.h"
#import "ControlVariables.h"
#import "User.h"

@interface LoginViewController ()

@end

@implementation LoginViewController

@synthesize mailTf;
@synthesize doButton;
@synthesize backgroundButton;
@synthesize scrollView;
@synthesize keyboardManager;
@synthesize memoMail;
@synthesize labelVersionName;


static int elementsRemaining = -1;


- (void) dealloc
{
    [mailTf release], mailTf = nil ;
    [doButton release], doButton = nil;
    [backgroundButton release], backgroundButton = nil;
    [scrollView release], scrollView = nil;
    [keyboardManager release], keyboardManager = nil;
    [memoMail release], memoMail = nil;
    [labelVersionName release], labelVersionName = nil;
    [super dealloc];
}

- (void)viewDidUnload
{
    self.mailTf = nil;
    self.doButton = nil;
    self.backgroundButton = nil;
    self.scrollView = nil;
    self.keyboardManager = nil;
    self.memoMail = nil;
    self.labelVersionName = nil;
    [super viewDidUnload];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    NSLocale *locale = [NSLocale currentLocale];
    NSString *countryCode = [locale objectForKey: NSLocaleCountryCode];
    NSString *serverName = DEBUG_LOCAL ? @"Local" :  STAGING_MODE ? @"Staging" :@"Producción";
    if ([countryCode isEqualToString:@"BO"])
        [DataLoader setUrlBaseGeneral:URL_BASE_GENERAL_BOLIVIA];
    else
        [DataLoader setUrlBaseGeneral:URL_BASE_GENERAL_ARGENTINA];
    if (STAGING_MODE)
        [DataLoader setUrlBaseGeneral:URL_BASE_GENERAL_STAGING];
    
    
    NSString *versionNumberForUser = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *countryName = [locale displayNameForKey: NSLocaleCountryCode value:countryCode];
    NSString *version = [NSString stringWithFormat:@"Versión %@ - %@ - %@",versionNumberForUser,serverName,countryName];
    [self.labelVersionName setText:version];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.keyboardManager = nil;
    [super viewWillDisappear:animated];
}

- (void)viewWillAppear:(BOOL)animated
{
    //[self.navigationController setNavigationBarHidden:YES animated:animated];
    [super viewWillAppear:animated];
    
    [SharedMemory createDirectory:DATA_DIRECTORY];
    
    self.keyboardManager = [[[KeyboardManager alloc] initWithDelegate:self.backgroundButton scrollView:self.scrollView elevation:180] autorelease];
    
    //In case the app has a problem and sends the user back to the Login screen, the shared memory should be cleaned.
    //[((SharedMemory*) [SharedMemory sharedInstance]) cleanLists];
    
    //make contentSize bigger than your scrollSize (you will need to figure out for your own use case)
    CGSize scrollContentSize = CGSizeMake(320, 345);
    self.scrollView.contentSize = scrollContentSize;
    
    
    // Set up the login form.
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if([defaults objectForKey:@"AuditLoginUser"]!=nil){
        self.memoMail = [defaults objectForKey:@"AuditLoginUser"];
        [self.mailTf setText:self.memoMail];
    }
    [self creatDictionaryOn:defaults key:UNSYNC_AUDITS_KEY];
    [self creatDictionaryOn:defaults key:ONEMONTH_AUDITS_KEY];
    [self creatDictionaryOn:defaults key:ONEMONTH_PDVS_KEY];
}

- (void) creatDictionaryOn:(NSUserDefaults*) defaults key:(NSString*) key
{
    if ([defaults objectForKey:key]==nil) {
        [defaults setObject:[[[NSMutableDictionary alloc]init]autorelease]  forKey:key];
        [defaults synchronize];
    }
}

- (bool) isLocationWaiter
{
    return true;
}


- (IBAction)doButtonTapped:(id)sender
{
    [self backgroundTapped:sender];
    
    self.memoMail = [self.mailTf text];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:self.memoMail forKey:@"AuditLoginUser"];
    [defaults synchronize];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = kLoadingMessage;
    
    elementsRemaining = 3;
    DataLoader *loader = [[DataLoader alloc] initWithCaller:self successSel:@selector(dataReadyWithLoader:) failureSel:@selector(dataNotReadyWithLoader:)];
    [loader loadUsers];
}

- (void) attemptLogin
{
    SharedMemory *mem = [SharedMemory sharedInstance];
    if(([mem.users count]==0 || [mem.auditTypes count]==0 || [mem.pointsOfSell count]==0)){
        [SharedMemory showError:kErrorMessageNotRespondingTitle andText:kErrorMessageNotResponding];
        return;
    }
    
    if ([self isValidUser]) {
        [self performSelectorOnMainThread:@selector(startLocationListSegue) withObject:nil waitUntilDone:NO];
    }
}

- (void)startLocationListSegue
{
    [self performSegueWithIdentifier:@"ToTabs" sender:self];
}


- (bool) isValidUser
{
    SharedMemory *mem = [SharedMemory sharedInstance];
    if([mem.users count]==0){
        [SharedMemory showError:kErrorMessageNotRespondingTitle andText:kErrorMessageNotResponding];
        return false;
    }
    
    bool found = false;
    int i = 0;
    while (!found && i< [mem.users count] ) {
        if([((User*)[mem.users objectAtIndex:i]).employeeId caseInsensitiveCompare:self.memoMail]==NSOrderedSame)
            found = true;
        i++;
    }
    
    if(found){
        mem.userIndex = i-1;
        return true;
    }
    else{
        [SharedMemory showError:kErrorUserNotFoundTitle andText:kErrorUserNotFound];
    }
    return false;
}

- (void)dataReadyWithLoader:(DataLoader*) dataLoader;
{
    @try {
        [dataLoader release];
    }
    @catch (NSException * e) { }
    
    elementsRemaining--;
    if (elementsRemaining==2) {
        
        if ([self isValidUser]) {
            DataLoader *loaderA = [[DataLoader alloc] initWithCaller:self successSel:@selector(dataReadyWithLoader:) failureSel:@selector(dataNotReadyWithLoader:)];
            [loaderA loadAuditTypes];
            DataLoader *loaderB = [[DataLoader alloc] initWithCaller:self successSel:@selector(dataReadyWithLoader:) failureSel:@selector(dataNotReadyWithLoader:)];
            [loaderB loadPointsOfSell:[LocationListenerViewController getLastGoodLocation]];
        }
        else{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            elementsRemaining = -1;
        }
    }
    else if (elementsRemaining==0) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self attemptLogin];
    }
}

- (void)dataNotReadyWithLoader:(DataLoader*) dataLoader;
{
    @try {
        [dataLoader release];
    }
    @catch (NSException * e) { }
    
    if (elementsRemaining!=-1){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [SharedMemory showError:kErrorMessageNotRespondingTitle andText:kErrorMessageNotResponding];
    }
    elementsRemaining = -1;
}

#pragma mark - Keyboard hiding


- (IBAction)backgroundTapped:(id)sender
{
	[self.mailTf resignFirstResponder];
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	[textField resignFirstResponder];
    return YES;
}




@end
